from pytrends.request import TrendReq
import matplotlib.pyplot as plt
import time
import sys
import pandas as pd
import numpy as np
import datetime as dt
import functions_trends_pers as ft

# Data
all_protests = pd.read_csv("../Data/sample.csv")

# Function to redo date range
def get_date_range(day_of):
    day = ft.get_day_num(day_of)
    day_s = day - 60
    if day_s < 0: # in case it goes back to previous year
        day_s = 365 + day_s
    day_e = day + 30
    year = int(day_of.split("/")[2]) # get year
    date_latest = ft.get_day_str(day_e, year)
    if day_s > day_e:
        year = year - 1
    date_earliest = ft.get_day_str(day_s, year)
    return date_earliest, date_latest

# term
term = ['protest']

# initialize collections
pred = TrendReq(hl='en-US', tz=360)

for i in range(0,len(all_protests)):
    geocode = all_protests['trends_code'].iloc[i]
    date = all_protests.iloc[i]['Date']
    date = dt.datetime.strptime(date, '%Y-%m-%d') #  Old line
    day_of = date.strftime('%-m/%-d/%Y')
    date_earliest, date_latest = get_date_range(day_of)
    # Get GT DATA
    d = ft.get_data(pred, term, geocode, date_earliest, date_latest)
    frame = pd.concat(d, axis=1, names=['Date'])
    frame.to_csv(''.join(all_protests['CityTown'][i] + '_' + day_of.replace("/", "_") + '_' + all_protests['type'][i] + '.csv'), index = ['date'], header=True)


